﻿using Zws.Common.ScanTool;
using Microsoft.AspNetCore.Builder;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Zws.Dapper.Filter;
using Zws.Dapper.Implements;
using Zws.Dapper.Interfaces;
using Zws.Frameworker.Module;

namespace Zws.Dapper
{
    public class ZwsDapperModule : ModuleMark

    {
        public void OnBuilderExec(WebApplicationBuilder builder)
        {
            //事务
            builder.Services.AddControllersWithViews(options =>
            {
                options.Filters.Add<UowActionFilter>();
            });
            //工作单元
            builder.Services.AddScoped<IUnitOfWork>(sp =>
            {
                //TODO 多个上下文再说吧
                var dbTypes = ScanHelper.ScanSpecialPublicClassByAssemblys(type =>
                type.IsAssignableTo(typeof(DbContext)) && !type.IsAbstract);
                if (dbTypes.Count == 0) throw new Exception("not find dbcontext class");
                var context = sp.GetService(dbTypes[0]);
                return new UnitOfWork((DbContext)context);
            });
        }
    }
}
